package com.hefan.pay.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.PaymentTypeEnum;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.CollectionUtils;
import com.hefan.common.pay.apple.AppleAppStoreVerifyRequest;
import com.hefan.common.util.PayPropertiesUtils;
import com.hefan.pay.bean.PayExtendVo;
import com.hefan.pay.bean.ThridPartyNotifyVo;
import com.hefan.pay.bean.TradeLog;
import com.hefan.pay.dao.PayReqLogDao;
import com.hefan.pay.itf.ThridPartyPayCallService;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lxw on 2016/10/19.
 */
@Component("appleAppStorePayService")
public class AppleAppStorePayServiceImpl implements ThridPartyPayCallService {

    private Logger logger = LoggerFactory.getLogger(AppleAppStorePayServiceImpl.class);

    @Resource
    private PayReqLogDao payReqLogDao;

    @Override
    public ResultBean thridPartyPayCall(PaymentTypeEnum paymentTypeEnum, TradeLog tradeLog, PayExtendVo payExtendVo) {
        Map returnMap = new HashMap();
        returnMap.put("orderId",payExtendVo.getOrderId());
        returnMap.put("payAmount",tradeLog.getPayAmount());
        returnMap.put("income",tradeLog.getIncome());
        returnMap.put("rewardFanpiao",tradeLog.getRewardFanpiao());
        returnMap.put("incomeAmount",tradeLog.getIncomeAmount());
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,returnMap);
        try {
            //记录操作日志
            this.payReqLogDao.savePayReqLog(payExtendVo.getOrderId(), payExtendVo.getUserId(), "apple app store", paymentTypeEnum.getPaymentType(), payExtendVo.getPaymentExtend(), "", resultBean.getCode());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ResultBean(ResultCode.UNSUCCESS,null);
        }
        return resultBean;
    }

    @Override
    public ResultBean thridPartyPayNotify(String orderId, ThridPartyNotifyVo thridPartyNotifyVo) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS, NOTFIY_EXCEPTION_IS_HANDLER);
        Map checkParamsMap = new HashMap();
        checkParamsMap.put("receipt-data",thridPartyNotifyVo.getAppleReceipt());
        String receiptDataJson = JSON.toJSONString(checkParamsMap);
        String md5Str  = DigestUtils.md5Hex(thridPartyNotifyVo.getAppleReceipt().getBytes(Charsets.UTF_8));
        String notifyResult = "";
        String transactionId = "";
        try {
            if(payReqLogDao.getAppleStoreReceiptCount(orderId,md5Str) > 0) { //检查评估验证码是否重复
                resultBean = new ResultBean(ResultCode.PayAppleStoreReceiptIsHad, NOTFIY_EXCEPTION_IS_HANDLER);
            }  else {
                 Map verifyMap = AppleAppStoreVerifyRequest.verifyReceipt(PayPropertiesUtils.getString("appleAppStoreVerifyReceipt"), receiptDataJson,thridPartyNotifyVo.getTransactionId());
                notifyResult = String.valueOf(verifyMap.get("resutl"));
                //logger.error("apple store notifyResult ------" + notifyResult);
                int resultStauts = Integer.valueOf(String.valueOf(verifyMap.get("status")));
                if (resultStauts == 21007) {  //本次支付为沙盒支付
                    if (!"165".equals(thridPartyNotifyVo.getUserId())) {  //非苹果审批账号 沙盒进行充值不进行饭票增加
                        resultBean = new ResultBean(ResultCode.PayAppleAppSandboxVerifyCode, NOTFIY_EXCEPTION_IS_HANDLER);
                    }
                } else if (resultStauts != 0) {
                    resultBean = new ResultBean(ResultCode.PayAppleAppStoreVerifyReceiptFail.get_code(),
                            ResultCode.PayAppleAppStoreVerifyReceiptFail.getMsg() + ";错误码：" + resultStauts, NOTFIY_EXCEPTION_IS_HANDLER);
                } else {
                    String bid = String.valueOf(verifyMap.get("bid"));
                    String productId = String.valueOf(verifyMap.get("productId"));
                    transactionId = String.valueOf(verifyMap.get("transactionId"));
                    if(!"com.starunion.hefanlive".equals(bid)) { //苹果内购支付使用的iPhone程序的bundle标识是否合法
                        resultBean = new ResultBean(ResultCode.PayAppleStoreReceiptError, NOTFIY_EXCEPTION_IS_HANDLER);
                    } else {
                        if(StringUtils.isBlank(productId) || StringUtils.isBlank(transactionId)) { //是否返回商品信息
                            resultBean = new ResultBean(ResultCode.PayAppleStoreNoPorductError, NOTFIY_EXCEPTION_IS_HANDLER);
                        } else {
                            //检查苹果支付的商品code是否合法
                            if (!StringUtils.isBlank(thridPartyNotifyVo.getIosProductCode()) && !thridPartyNotifyVo.getIosProductCode().equals(productId)) {
                                resultBean = new ResultBean(ResultCode.PayAppleStorePorductError, NOTFIY_EXCEPTION_IS_HANDLER);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            resultBean = new ResultBean(ResultCode.UNSUCCESS,NOTFIY_EXCEPTION_IS_NOT_HANDLER);
        }
        logger.info("AppleAppStorePayServiceImpl--thridPartyPayNotify---result:{}",JSON.toJSONString(resultBean));
        payReqLogDao.updatePayReqNotifyInfoForAppleStore(orderId,resultBean.getCode(),notifyResult, receiptDataJson,md5Str,transactionId);
        return resultBean;
    }

    @Override
    public ResultBean<ThridPartyNotifyVo> thridPartyPayNotifyParse(ThridPartyNotifyVo thridPartyNotifyVo) {
        return new ResultBean<ThridPartyNotifyVo>(ResultCode.SUCCESS, thridPartyNotifyVo);
    }

}
